package com.wzq.solution;

import com.wzq.solution.node.ListNode;

class Solution61 {
    public static ListNode rotateRight(ListNode head, int k) {
        ListNode p1=head;
        ListNode p2=head;
        while(k-- >0){
            if(p1.next != null){
                p1 = p1.next;
            }else{
                p1 = head;
            }
            
        }
        ListNode tail=null;
        while(p1.next != null){
            p1 = p1.next;
            tail = p2;
            p2 = p2.next;
        }
        p1.next = head;
        tail.next = null;
        return p2;
        
    }


    public static ListNode rotateRight2(ListNode head, int k) {
        if(head == null || k==0){
            return head;
        }

        int n=1;
        ListNode p1=head;
        while(p1.next != null){
            n++;
            p1 = p1.next;
        }

        k = k%n;
        n = n-k;

        ListNode p2=head;
        while(n-- > 1){
            p2 = p2.next;
        }
        p1.next = head;
        head = p2.next;
        p2.next = null;

        return head;

    }


    public static void main(String[] args) {
        int[] headArr = new int[]{1,2,3,4,5};
        ListNode head = new ListNode(headArr[0]);
        ListNode p =head;
        for (int i=1;i<headArr.length; i++){
            p.next = new ListNode(headArr[i]);
            p = p.next;
        }
        rotateRight2(head,7);
    }
}